package com.zc.im.jpa.converter;

import com.zc.im.common.constant.enums.BaseEnum;

import javax.persistence.AttributeConverter;
import java.util.Arrays;

/**
 * Project：im
 * Date：2022/4/20
 * Time：17:43
 * Description：抽象转换器
 *
 * @author Challen.Zhang
 * @version 1.0
 */
public abstract class AbstractEnumConverter<ENUM extends Enum<ENUM> & BaseEnum<ENUM, D>, D> implements AttributeConverter<ENUM, D> {

    private final Class<ENUM> type;

    public AbstractEnumConverter(Class<ENUM> type) {
        this.type = type;
    }

    @Override
    public D convertToDatabaseColumn(ENUM attribute) {
        return attribute != null ? attribute.getValue() : null;
    }

    @Override
    public ENUM convertToEntityAttribute(D dbData) {
        return dbData != null ?
                Arrays.stream(type.getEnumConstants())
                .filter(x -> x.getValue() == dbData)
                .findFirst()
                .orElse(null)
                : null;
    }

}
